package com.xm.transfer.service.impl;

import com.xm.transfer.annotations.Autowired;
import com.xm.transfer.annotations.Service;
import com.xm.transfer.annotations.Transactional;
import com.xm.transfer.dao.AccountDao;
import com.xm.transfer.pojo.Account;
import com.xm.transfer.service.TransferService;

@Service
public class TransferServiceImpl implements TransferService {

    @Autowired
    private AccountDao accountDao;

    // 需事务控制
    /*
    事务传播性
    required:当前有事务，则加入事务，没有事务，新开启一个事务
    required_new:无论当前是否有事务，都开启新事务
    supports:不需要事务上下文，如果存在事务，则加入事务
    not_supports:当前方法不能在事务中执行，否者抛出异常
    never:不需要事务上下文，如果存在事务，则抛出异常
    nested:嵌套事务，独立提交或回滚
    mandatory:必须有事务运行，否者抛出异常
     */
    /*
    数据库隔离性
    未读提交：出现脏读，不可重复读，幻读
    已读提交：出现不可重复读，幻读
    可重复读：出现幻读
    可串行化：都不出现
    MVCC
     */
    @Override
    @Transactional
    public void transfer(String from, String to, double money) throws Exception {
        System.out.println(from);
        Account formAccount = accountDao.selectAccountByCardNo(from);
        System.out.println(formAccount.toString());
        System.out.println(to);
        Account toAccount = accountDao.selectAccountByCardNo(to);
        System.out.println(toAccount.toString());
        formAccount.setAmount(formAccount.getAmount() - money);
        toAccount.setAmount(toAccount.getAmount() + money);
        accountDao.updateAccountByCardNo(formAccount);
        accountDao.updateAccountByCardNo(toAccount);
    }
}
